package com.flx.aop;

import com.flx.mapper.OperationLogMapper;
import entity.OperationLog;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import utils.JwtUtil;

import java.time.LocalDateTime;

/**
 * @ClassName OperateLogAspect
 * 记录操作日志
 * @Author 23207
 * @Date 2025/4/18 14:48
 * @Version 1.0
 */
@Aspect
@Component
@Slf4j
public class OperateLogAspect {
  @Autowired
  private HttpServletRequest request;
  @Autowired
  private OperationLogMapper operationLogMapper;

  @Around("@annotation(com.flx.anno.OperateLog)")
  public Object OperateLog(ProceedingJoinPoint joinPoint) throws Throwable {
    System.out.println("记录日志");
    String token = request.getHeader("token");
    Claims claims = JwtUtil.parseToken(token);
    String userName = claims.get("userName", String.class);

    String className = joinPoint.getClass().getName();
    String methodName = joinPoint.getSignature().getName();
    // 路径参数怎么获取
    String url = request.getRequestURI();
    String args = joinPoint.getArgs().toString();
    LocalDateTime dateTime = LocalDateTime.now();
    // System.out.println("类名：" + className + " 方法名：" + methodName + " 参数：" + args + " 时间：" + dateTime);

    long begin = System.currentTimeMillis();
    Object result = joinPoint.proceed();
    long end = System.currentTimeMillis();

    OperationLog operationLog = OperationLog.builder()
            .userName(userName)
            .className(className)
            .methodName(methodName)
            .url(url)
            .args(args)
            .coseTime(end - begin)
            .createTime(dateTime)
            .build();
    operationLogMapper.insert(operationLog);
    return result;
  }
}
